// 实现这个项目的构建任务

const sass = require("sass");
const loadGruntTasks = require("load-grunt-tasks");

module.exports = (grunt) => {
  grunt.initConfig({
    // 将 sass 转为 css
    sass: {
      options: {
        sourceMap: true,
        implementation: sass,
      },
      main: {
        files: {
          "dist/assets/styles/main.css": "src/styles/main.scss",
        },
      },
    },
    // 编译 JavaScript
    babel: {
      options: {
        sourceMap: true,
        presets: ["@babel/preset-env"],
      },
      main: {
        files: {
          "dist/assets/scripts/main.js": "src/assets/scripts/main.js",
        },
      },
    },
    // 压缩 js
    uglify: {
      my_target: {
        files: {
          "dist/assets/scripts/main.min.js": ["dist/assets/scripts/main.js"],
        },
      },
    },
    // 编译模板
    web_swig: {
      options: {
        swigOptions: {
          //缓存设置为false
          cache: false,
        },
        getData: function (tpl) {
          //模板文件的数据
          return { myGruntTitle: "hello,grunt-web-swig" };
        },
      },
      main: {
        expand: true,
        cwd: "src/", //源文件文件夹
        src: "**/*.html", //后缀名匹配
        dest: "dist/", //目标文件夹
      },
    },
    // 拷贝静态文件
    copy: {
      main: {
        expand: true,
        src: "public/*",
        dest: "dist/",
      },
    },
    // 监视
    watch: {
      js: {
        files: ["src/js/*.js"],
        tasks: ["babel"],
      },
      css: {
        files: ["src/scss/*.scss"],
        tasks: ["sass"],
      },
      html: {
        files: ["src/*.html"],
        tasks: ["web_swig"],
      },
    },
    // 清除
    clean: {
      temp: "temp/**",
    },
  });

  grunt.loadNpmTasks("grunt-contrib-clean"); // 清理
  loadGruntTasks(grunt); // 自动加载所有插件
  grunt.registerTask("default", [
    "clean",
    "web_swig",
    "sass",
    "babel",
    "uglify",
    "copy",
    "watch",
  ]);
};
